package com.xiaoxu.rental.security;

import com.xiaoxu.rental.entity.Permission;
import com.xiaoxu.rental.entity.User;

import com.xiaoxu.rental.service.PermissionService;
import com.xiaoxu.rental.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @Title: CustomerUserDetailsService
 * @Author Mr.Xu
 * @Package com.xiaoxu.rental.security
 * @Date 2024/7/25 14:14
 * @description: SpringSecurity
 */
@Component
public class CustomerUserDetailsService implements UserDetailsService {
    @Resource
    private UserService userService;
    @Resource
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=userService.selectByUsername(username);//到数据库中按username查询
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //查询 权限 列表----------------------------
        Integer userId = user.getId();
        //查询用户权限列表
        List<Permission> permissions = permissionService.selectPermissionListByUserId(userId);
        user.setPermissionList(permissions);
        //通过stream流处理，将权限对象转换为权限字符串列表 也就是获取permission_coder
        List<String> list = permissions.stream()
                .filter(Objects::nonNull)
                .map(Permission::getPermissionCode)
                .filter(Objects::nonNull)
                .toList();
        String[] array = list.toArray(new String[list.size()]);
        List<GrantedAuthority> authorityList= AuthorityUtils.createAuthorityList(array);
        user.setAuthorities(authorityList);
        System.out.println(user); //做显示判断是否有哦?
        //authorities=[sys:manager,  李四登录的情况下
        // sys:user, sys:dept, sys:role,
        // sys:user:add, sys:user:delete,
        // sys:user:edit, sys:user:select,
        // sys:dept:add, sys:dept:delete,
        // sys:dept:edit, sys:dept:select,
        // sys:role:select],
        return user;
    }
}
